import request from './index';
import { cacheManager } from '../utils/cacheManager';
import { requestManager } from '../utils/requestManager';

// ================== 通用响应处理工具 ==================

/**
 * 标准化API响应，统一处理不同格式的响应
 */
function normalizeApiResponse<T>(response: any): ApiResponse<T> {
  // 处理标准分页格式 {rows, total, code, msg}
  if ('rows' in response && 'total' in response) {
    return {
      success: response.code === 200,
      data: response.rows,
      total: response.total,
      message: response.msg,
      code: response.code
    };
  }
  
  // 处理简单格式 {data, code, msg}
  if ('data' in response) {
    return {
      success: response.code === 200 || response.code === undefined,
      data: response.data,
      message: response.msg,
      code: response.code
    };
  }
  
  // 直接返回数据（兜底处理）
  return {
    success: true,
    data: response
  };
}

// 移除未使用的 isApiSuccess 函数，已集成到 normalizeApiResponse 中

// ================== 参数验证工具 ==================

/**
 * 验证分页参数
 */
function validatePaginationParams(params: { pageNum?: number; pageSize?: number }): void {
  if (params.pageNum !== undefined && (params.pageNum < 1 || !Number.isInteger(params.pageNum))) {
    throw new Error('pageNum必须是大于0的整数');
  }
  
  if (params.pageSize !== undefined && (params.pageSize < 1 || params.pageSize > 1000 || !Number.isInteger(params.pageSize))) {
    throw new Error('pageSize必须是1-1000之间的整数');
  }
}

/**
 * 验证必填参数
 */
function validateRequired<T>(value: T, fieldName: string): asserts value is NonNullable<T> {
  if (value === null || value === undefined || value === '') {
    throw new Error(`参数 ${fieldName} 是必填的`);
  }
}

/**
 * 标准化分页参数
 */
function normalizePaginationParams(params?: { pageNum?: number; pageSize?: number }) {
  const normalized = {
    pageNum: params?.pageNum || 1,
    pageSize: params?.pageSize || 20
  };
  
  validatePaginationParams(normalized);
  return normalized;
}

// ================== 缓存策略工具 ==================

/**
 * 生成稳定的缓存键
 */
function generateCacheKey(prefix: string, params: Record<string, any>): string {
  // 排序参数键，确保相同参数生成相同的缓存键
  const sortedParams = Object.keys(params)
    .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
    .sort()
    .map(key => `${key}:${JSON.stringify(params[key])}`)
    .join('|');
  
  return sortedParams ? `${prefix}_${sortedParams}` : prefix;
}

/**
 * 智能缓存时间计算
 */
function calculateCacheTime(dataType: 'static' | 'semi-static' | 'dynamic' | 'realtime'): number {
  switch (dataType) {
    case 'static':     return 60 * 60 * 1000;     // 1小时 - 国家列表等
    case 'semi-static': return 30 * 60 * 1000;    // 30分钟 - 短剧详情等
    case 'dynamic':    return 10 * 60 * 1000;     // 10分钟 - 短剧列表等
    case 'realtime':   return 2 * 60 * 1000;      // 2分钟 - 字幕数据等
    default:          return 10 * 60 * 1000;
  }
}

// 移除未使用的 clearRelatedCache 函数

// ================== 业务验证工具 ==================

/**
 * 验证短剧相关参数
 */
function validateDramaParams(params: { id?: number | string; title?: string; status?: number }): void {
  if (params.title !== undefined && typeof params.title !== 'string') {
    throw new Error('标题必须是字符串');
  }
  
  if (params.status !== undefined && (typeof params.status !== 'number' || params.status < 0)) {
    throw new Error('状态必须是非负整数');
  }
  // ID验证由 safeParseInt 处理，避免重复
}

/**
 * 验证剧集相关参数
 */
function validateEpisodeParams(params: { shortDramaId?: number; episodeId?: number }): void {
  if (params.shortDramaId !== undefined) {
    if (typeof params.shortDramaId !== 'number' || params.shortDramaId < 1) {
      throw new Error('短剧ID必须是有效的正整数');
    }
  }
  
  if (params.episodeId !== undefined) {
    if (typeof params.episodeId !== 'number' || params.episodeId < 1) {
      throw new Error('剧集ID必须是有效的正整数');
    }
  }
}

/**
 * 安全的参数转换
 */
function safeParseInt(value: any, fieldName: string): number {
  if (value === undefined || value === null) {
    throw new Error(`${fieldName} 不能为空`);
  }
  
  const parsed = typeof value === 'string' ? parseInt(value, 10) : Number(value);
  if (isNaN(parsed) || parsed < 1) {
    throw new Error(`${fieldName} 必须是有效的正整数`);
  }
  
  return parsed;
}

// 移除未使用的 logApiCall 函数

// ================== 搜索工具函数 ==================

/**
 * 搜索关键词清理和标准化
 */
function normalizeSearchKeyword(keyword: string): string {
  return keyword
    .trim()
    .toLowerCase()
    .replace(/\s+/g, ' ')  // 合并多个空格
    .replace(/[^\w\s\u4e00-\u9fa5]/g, ''); // 保留中文、字母、数字
}

/**
 * 构建搜索参数
 */
function buildSearchParams(params: AdvancedSearchParams): DramaListParams {
  const searchParams: DramaListParams = {
    pageNum: params.pageNum,
    pageSize: params.pageSize,
  };

  // 处理搜索关键词
  if (params.keyword) {
    const normalizedKeyword = normalizeSearchKeyword(params.keyword);
    if (normalizedKeyword) {
      searchParams.title = normalizedKeyword; // 当前API使用title字段搜索
    }
  }

  // 处理筛选条件
  if (params.status !== undefined) searchParams.status = params.status;
  if (params.special) searchParams.special = params.special;
  if (params.categoryName) searchParams.categoryName = params.categoryName;

  // 处理排序
  if (params.sortBy) {
    let orderBy: string = params.sortBy;
    if (params.sortDirection === 'desc') {
      orderBy = `-${orderBy}`; // 假设API支持负号表示降序
    }
    searchParams.orderBy = orderBy;
  }

  // 处理多个分类（如果API支持）
  if (params.categories && params.categories.length > 0) {
    searchParams.categoryName = params.categories.join(',');
  }

  // 处理多个状态（如果API支持）
  if (params.statusList && params.statusList.length > 0) {
    searchParams.status = params.statusList[0]; // 当前API可能只支持单个状态
  }

  return searchParams;
}

/**
 * 防抖搜索辅助函数
 */
class SearchDebouncer {
  private timeouts = new Map<string, number>();

  debounce<T extends any[]>(
    key: string,
    fn: (...args: T) => void,
    delay: number = 300
  ): (...args: T) => void {
    return (...args: T) => {
      if (this.timeouts.has(key)) {
        clearTimeout(this.timeouts.get(key)!);
      }

      const timeout = setTimeout(() => {
        fn(...args);
        this.timeouts.delete(key);
      }, delay) as number;

      this.timeouts.set(key, timeout);
    };
  }

  cancel(key: string): void {
    if (this.timeouts.has(key)) {
      clearTimeout(this.timeouts.get(key)!);
      this.timeouts.delete(key);
    }
  }

  clear(): void {
    this.timeouts.forEach(timeout => clearTimeout(timeout));
    this.timeouts.clear();
  }
}

// 全局搜索防抖器实例
const searchDebouncer = new SearchDebouncer();

/**
 * 搜索缓存管理
 */
class SearchCacheManager {
  private readonly SEARCH_CACHE_PREFIX = 'search_';
  private readonly SUGGESTION_CACHE_PREFIX = 'suggestions_';

  getCachedSearch<T>(params: AdvancedSearchParams): T | null {
    const cacheKey = this.generateSearchCacheKey(params);
    return cacheManager.get<T>(cacheKey);
  }

  setCachedSearch<T>(params: AdvancedSearchParams, result: T, ttl: number = 5 * 60 * 1000): void {
    const cacheKey = this.generateSearchCacheKey(params);
    cacheManager.set(cacheKey, result, ttl);
  }

  getCachedSuggestions(keyword: string): string[] | null {
    const cacheKey = `${this.SUGGESTION_CACHE_PREFIX}${normalizeSearchKeyword(keyword)}`;
    return cacheManager.get<string[]>(cacheKey);
  }

  setCachedSuggestions(keyword: string, suggestions: string[], ttl: number = 30 * 60 * 1000): void {
    const cacheKey = `${this.SUGGESTION_CACHE_PREFIX}${normalizeSearchKeyword(keyword)}`;
    cacheManager.set(cacheKey, suggestions, ttl);
  }

  private generateSearchCacheKey(params: AdvancedSearchParams): string {
    const keyParams = {
      keyword: params.keyword ? normalizeSearchKeyword(params.keyword) : '',
      searchType: params.searchType || 'title',
      pageNum: params.pageNum || 1,
      pageSize: params.pageSize || 20,
      ...buildSearchParams(params)
    };
    return generateCacheKey(this.SEARCH_CACHE_PREFIX, keyParams);
  }

  clearSearchCache(): void {
    // 注意：这里需要cacheManager支持按前缀清除
    // 如果不支持，可以记录所有搜索相关的缓存key来批量清除
    console.log('清除搜索缓存');
  }
}

// 全局搜索缓存管理器实例
const searchCacheManager = new SearchCacheManager();

// ================== 类型定义 ==================

export interface Drama {
  id: number;
  title: string;
  coverImageUrl: string;
  description: string;
  episodeCount: number; // API文档显示可能是字符串，但这里保持number更合理
  score: string;
  categoryName: string[];
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
  remark?: string;
  status?: number;
  special?: string;
  clickCount?: number;
  likeCount?: number;
  real?: number; // 添加缺失的字段：当前实际更新集数
  subtitleStatus?: number; // 字幕状态：0-已完成，1-未完成
}

export interface Episode {
  episodeId: number;
  videoUrl: string;
  shortDramaId: number;
  vip: boolean;
  status: number;
}

export interface LanguageOption {
  countryId: number;
  countryName: string;
  countryLanguage: string;
  status: number;
}

export interface Subtitle {
    id: number;
    subtitleId: number;      // 新增：字幕ID，用于删除操作
    episodeId: number;
    countryId: number;
    subtitleFile: string;
    language: string;
    status: number;          // 新增：字幕状态
    shortDramaId: number;    // 新增：短剧ID
    countryName: string;     // 新增：国家名称
    countryLanguage: string; // 新增：国家语言
}

export interface SubtitleCompletionStatus {
    uploadedSubtitles: number;    // 已经上传了字幕的集数
    subtitleStatus: number;       // 上传状态(0：完成，1：未完成)
    message: string;              // 状态描述
    shortDramaId: number;         // 短剧id
    missingSubtitles: number;     // 未上传字幕的集数
    totalEpisodes: number;        // 短剧的总集数
}

// ================== 统一API响应格式 ==================

// 标准分页响应格式
export interface ApiResult<T> {
  rows: T;
  total: number;
  code: number;
  msg: string;
}

// 简单响应格式（用于下拉框等不需要分页的数据）
export interface SimpleApiResult<T> {
  data: T;
  code: number;
  msg: string;
}

// 通用响应处理器
export interface ApiResponse<T> {
  success: boolean;
  data: T;
  total?: number;
  message?: string;
  code?: number;
}

// TODO: 统一所有API响应格式
// 当前问题：部分API返回 {data: T}，部分返回 {rows: T, total, code, msg}
// 建议：所有API都使用 ApiResult<T> 格式

// 添加查询参数的类型定义
export interface DramaListParams {
  pageNum?: number;
  pageSize?: number;
  title?: string;          // 短剧名称搜索
  status?: number;         // 状态筛选
  special?: string;        // 特殊标签
  categoryName?: string;   // 分类名称
  orderBy?: string;        // 排序字段
  [key: string]: any;      // 兼容其他参数
}

// 字幕查询参数类型定义
export interface SubtitleListParams {
  pageNum?: number;
  pageSize?: number;
  episodeId?: number;      // 剧集ID
  countryId?: number;      // 国家/语言ID
  language?: string;       // 语言代码
  shortDramaId?: number;   // 短剧ID（用于批量查询）
  [key: string]: any;      // 兼容其他参数
}

// ================== 搜索功能增强接口 ==================

// 搜索类型枚举
export enum SearchType {
  TITLE = 'title',           // 标题搜索
  KEYWORD = 'keyword',       // 关键词搜索
  CATEGORY = 'category',     // 分类搜索
  ADVANCED = 'advanced'      // 高级搜索
}

// 排序选项
export enum SortOrder {
  RELEVANCE = 'relevance',   // 相关性排序
  CREATE_TIME = 'createTime', // 创建时间
  UPDATE_TIME = 'updateTime', // 更新时间
  CLICK_COUNT = 'clickCount', // 点击量
  LIKE_COUNT = 'likeCount',   // 喜欢数
  SCORE = 'score'            // 评分
}

// 高级搜索参数
export interface AdvancedSearchParams extends Omit<DramaListParams, 'title'> {
  keyword?: string;          // 搜索关键词
  searchType?: SearchType;   // 搜索类型
  
  // 筛选条件
  categories?: string[];     // 多个分类
  statusList?: number[];     // 多个状态
  specialTags?: string[];    // 多个特殊标签
  
  // 数值范围筛选
  scoreRange?: [number, number];     // 评分范围
  episodeRange?: [number, number];   // 集数范围
  clickRange?: [number, number];     // 点击量范围
  
  // 时间范围筛选
  createTimeRange?: [string, string]; // 创建时间范围
  updateTimeRange?: [string, string]; // 更新时间范围
  
  // 排序设置
  sortBy?: SortOrder;        // 排序字段
  sortDirection?: 'asc' | 'desc'; // 排序方向
  
  // 搜索增强
  exactMatch?: boolean;      // 精确匹配
  includeDescription?: boolean; // 包含描述搜索
}

// 搜索结果接口
export interface SearchResult<T> extends ApiResult<T> {
  searchKeyword?: string;    // 搜索关键词
  searchTime: number;        // 搜索耗时(ms)
  suggestions?: string[];    // 搜索建议
  filters?: SearchFilters;   // 可用筛选器
}

// 搜索筛选器
export interface SearchFilters {
  availableCategories: Array<{ name: string; count: number }>;
  availableStatuses: Array<{ status: number; name: string; count: number }>;
  availableSpecialTags: Array<{ tag: string; count: number }>;
  scoreRange: [number, number];
  episodeRange: [number, number];
}

// 剧集查询参数类型定义
export interface EpisodeListParams {
  shortDramaId: number;    // 必填：短剧ID
  pageNum?: number;
  pageSize?: number;
  status?: number;         // 剧集状态
  vip?: boolean;           // 是否VIP专享
  [key: string]: any;
}

// ================== API 函数 ==================

/**
 * 获取短剧详情
 * @param id 短剧ID
 */
export async function getDramaDetails(id: string | number): Promise<Drama> {
  // 参数验证
  validateRequired(id, 'id');
  const numericId = safeParseInt(id, '短剧ID');
  const cacheKey = `drama_details_${numericId}`;

  // 尝试从缓存获取
  const cached = cacheManager.get<Drama>(cacheKey);
  if (cached) {
    return cached;
  }

  const config = {
    url: '/api/asimplefox/short/drama/list',
    params: { id: numericId },
    method: 'GET' as const
  };

  try {
    const result = await requestManager.request(
      () => request.get<ApiResult<Drama[]>, ApiResult<Drama[]>>(config.url, { params: config.params }),
      config,
      { enableDeduplication: true }
    );

    // 使用统一响应处理
    const normalizedResponse = normalizeApiResponse<Drama[]>(result);
    
    if (!normalizedResponse.success) {
      throw new Error(normalizedResponse.message || `获取短剧详情失败 (ID: ${numericId})`);
    }

    const dramas = normalizedResponse.data;
    if (!dramas || dramas.length === 0) {
      throw new Error(`未找到ID为 ${numericId} 的短剧信息`);
    }

    const drama = dramas[0];
    // 缓存结果
    cacheManager.set(cacheKey, drama, 10 * 60 * 1000); // 10分钟缓存
    return drama;
  } catch (error) {
    console.error(`获取短剧详情失败 (ID: ${numericId}):`, error);
    throw error instanceof Error ? error : new Error(`获取短剧详情失败: ${error}`);
  }
}

/**
 * 获取短剧的剧集列表, 会自动处理分页以获取全部数据
 * @param shortDramaId 短剧ID
 */
export async function getDramaEpisodes(shortDramaId: string | number): Promise<Episode[]> {
  // 参数验证
  const numericDramaId = safeParseInt(shortDramaId, '短剧ID');
  validateEpisodeParams({ shortDramaId: numericDramaId });
  const cacheKey = `drama_episodes_${numericDramaId}`;

  // 尝试从缓存获取
  const cached = cacheManager.get<Episode[]>(cacheKey);
  if (cached) {
    return cached;
  }

  const pageSize = 100;

  const fetchPage = (pageNum: number) => {
    const config = {
      url: '/api/asimplefox/short/drama/episode/list',
      params: { shortDramaId: numericDramaId, pageNum, pageSize },
      method: 'GET' as const
    };

    return requestManager.request(
      () => request.get<ApiResult<Episode[]>, ApiResult<Episode[]>>(config.url, { params: config.params }),
      config,
      { enableDeduplication: true }
    );
  };

  // 获取第一页数据来确定总数
  const firstPage = await fetchPage(1);

  // 检查是否有数据
  if (!firstPage.rows || firstPage.total === 0) {
    const emptyResult: Episode[] = [];
    cacheManager.set(cacheKey, emptyResult, 2 * 60 * 1000); // 空结果缓存2分钟
    return emptyResult;
  }

  const { rows: firstPageRows, total } = firstPage;
  const allEpisodes = firstPageRows;

  // 如果第一页已经包含了所有数据，直接返回
  if (allEpisodes.length >= total) {
    cacheManager.set(cacheKey, allEpisodes, 5 * 60 * 1000); // 5分钟缓存
    return allEpisodes;
  }

  // 计算需要请求的剩余页数
  const totalPages = Math.ceil(total / pageSize);
  const requests = [];
  for (let pageNum = 2; pageNum <= totalPages; pageNum++) {
    requests.push({
      requestFn: () => fetchPage(pageNum),
      config: {
        url: '/api/asimplefox/short/drama/episode/list',
        params: { shortDramaId: numericDramaId, pageNum, pageSize },
        method: 'GET' as const
      }
    });
  }

  // 使用批量请求管理器
  const remainingPages = await requestManager.batchRequest(requests, {
    concurrency: 3, // 限制并发数
    failFast: false // 不因单个失败而终止
  });

  // 合并所有页面的结果
  for (const page of remainingPages) {
    if (page?.rows) {
      allEpisodes.push(...page.rows);
    }
  }

  // 缓存结果
  cacheManager.set(cacheKey, allEpisodes, 5 * 60 * 1000); // 5分钟缓存
  return allEpisodes;
}

/**
 * 获取短剧列表 (可用于常规列表页)
 * @param params 查询参数
 */
export function getDramaList(params?: DramaListParams): Promise<ApiResult<Drama[]>> {
  // 参数验证
  if (params) {
    validatePaginationParams(params);
    validateDramaParams(params); // 验证title、status等业务参数
  }

  // 标准化分页参数
  const normalizedParams = normalizePaginationParams(params);
  
  // 合并所有参数，确保包含排序
  const requestParams = {
    ...normalizedParams,
    ...params,
    // 确保有明确的排序参数 - 按ID升序排列
    orderBy: params?.orderBy || 'id'
  };

  const config = {
    url: '/api/asimplefox/short/drama/list',
    params: requestParams,
    method: 'GET' as const
  };

  return requestManager.request(
    () => request.get<ApiResult<Drama[]>, ApiResult<Drama[]>>(config.url, { params: config.params }),
    config,
    { enableDeduplication: true }
  );
}

/**
 * 获取短剧分页数据 (优化版本，支持真正的分页)
 * @param pageNum 页码
 * @param pageSize 每页大小
 * @param filters 额外的筛选条件
 */
export async function getDramasPaginated(
  pageNum: number = 1, 
  pageSize: number = 20,
  filters?: Omit<DramaListParams, 'pageNum' | 'pageSize'>
): Promise<ApiResult<Drama[]>> {
  // 参数验证
  validatePaginationParams({ pageNum, pageSize });

  const params = { pageNum, pageSize, ...filters };
  const cacheKey = generateCacheKey('dramas_paginated', params);

  // 尝试从缓存获取
  const cached = cacheManager.get<ApiResult<Drama[]>>(cacheKey);
  if (cached) {
    return cached;
  }

  try {
    const result = await getDramaList(params);

    // 使用智能缓存时间
    const cacheTime = calculateCacheTime('dynamic');
    cacheManager.set(cacheKey, result, cacheTime);
    return result;
  } catch (error) {
    console.error('获取分页短剧列表失败:', error);
    throw error instanceof Error ? error : new Error(`获取短剧列表失败: ${error}`);
  }
}

/**
 * 获取所有短剧列表 (保留兼容性，但建议使用分页版本)
 * @deprecated 建议使用 getDramasPaginated 进行分页加载
 */
export async function getAllDramas(): Promise<Drama[]> {
  const cacheKey = 'all_dramas';

  // 尝试从缓存获取
  const cached = cacheManager.get<Drama[]>(cacheKey);
  if (cached) {
    return cached;
  }

  const pageSize = 100;

  const fetchPage = (pageNum: number) => getDramaList({ pageNum, pageSize });

  // 获取第一页数据来确定总数
  const firstPage = await fetchPage(1);

  // 检查是否有数据
  if (!firstPage.rows || firstPage.total === 0) {
    const emptyResult: Drama[] = [];
    cacheManager.set(cacheKey, emptyResult, 2 * 60 * 1000); // 空结果缓存2分钟
    return emptyResult;
  }

  const { rows: firstPageRows, total } = firstPage;
  const allDramas = firstPageRows;

  // 如果第一页已经包含了所有数据，直接返回
  if (allDramas.length >= total) {
    cacheManager.set(cacheKey, allDramas, 10 * 60 * 1000); // 10分钟缓存
    return allDramas;
  }

  // 计算需要请求的剩余页数
  const totalPages = Math.ceil(total / pageSize);
  const requests = [];
  for (let pageNum = 2; pageNum <= totalPages; pageNum++) {
    requests.push({
      requestFn: () => fetchPage(pageNum),
      config: {
        url: '/api/asimplefox/short/drama/list',
        params: { pageNum, pageSize },
        method: 'GET' as const
      }
    });
  }

  // 使用批量请求管理器
  const remainingPages = await requestManager.batchRequest(requests, {
    concurrency: 3, // 限制并发数
    failFast: false // 不因单个失败而终止
  });

  // 合并所有页面的结果
  for (const page of remainingPages) {
    if (page?.rows) {
      allDramas.push(...page.rows);
    }
  }

  // 缓存结果
  cacheManager.set(cacheKey, allDramas, 10 * 60 * 1000); // 10分钟缓存
  return allDramas;
}

/**
 * 获取国家/地区选择列表
 */
export async function getCountrySelectList(): Promise<LanguageOption[]> {
  const cacheKey = generateCacheKey('country_select_list', {});

  // 尝试从缓存获取
  const cached = cacheManager.get<LanguageOption[]>(cacheKey);
  if (cached) {
    return cached;
  }

  const config = {
    url: '/api/asimplefox/short/drama/country/select',
    method: 'GET' as const
  };

  try {
    const result = await requestManager.request(
      () => request.get<SimpleApiResult<LanguageOption[]>, SimpleApiResult<LanguageOption[]>>(config.url),
      config,
      { enableDeduplication: true }
    );

    // 使用统一响应处理
    const normalizedResponse = normalizeApiResponse<LanguageOption[]>(result);
    
    if (!normalizedResponse.success) {
      throw new Error(normalizedResponse.message || '获取国家列表失败');
    }

    const countries = normalizedResponse.data || [];
    
    // 验证数据格式
    const validCountries = countries.filter(country => 
      country && 
      typeof country.countryId === 'number' && 
      typeof country.countryName === 'string' &&
      country.countryName.trim() !== ''
    );

    if (validCountries.length !== countries.length) {
      console.warn(`过滤了 ${countries.length - validCountries.length} 条无效的国家数据`);
    }

    // 使用智能缓存时间（国家数据相对稳定）
    const cacheTime = calculateCacheTime('static');
    cacheManager.set(cacheKey, validCountries, cacheTime);
    return validCountries;
  } catch (error) {
    console.error('获取国家选择列表失败:', error);
    // 返回空数组作为降级方案
    return [];
  }
}

/**
 * 获取字幕列表 (分页)
 * @param params 查询参数
 */
export function getSubtitleList(params?: SubtitleListParams): Promise<ApiResult<Subtitle[]>> {
  // 参数验证
  if (params) {
    validatePaginationParams(params);
    
    // 验证业务参数
    if (params.episodeId !== undefined && (params.episodeId < 1 || !Number.isInteger(params.episodeId))) {
      throw new Error('episodeId必须是大于0的整数');
    }
    
    if (params.countryId !== undefined && (params.countryId < 1 || !Number.isInteger(params.countryId))) {
      throw new Error('countryId必须是大于0的整数');
    }
  }

  const config = {
    url: '/api/asimplefox/short/drama/subtitle/list',
    params: { ...params, ...normalizePaginationParams(params) },
    method: 'GET' as const
  };

  return requestManager.request(
    () => request.get<ApiResult<Subtitle[]>, ApiResult<Subtitle[]>>(config.url, { params: config.params }),
    config,
    { enableDeduplication: true }
  );
}

/**
 * 根据剧集ID获取字幕列表 (优化版本 - 流式加载)
 * @param episodeIds 剧集ID数组 - 一个短剧包含多个剧集，每个剧集有自己的episodeId
 * @param onProgress 进度回调函数，每获取到一个剧集的字幕就调用一次
 * @param forceRefresh 是否强制刷新，忽略缓存
 */
export async function getSubtitlesByEpisodeIds(
  episodeIds: number[],
  onProgress?: (subtitles: Subtitle[], completedCount: number, totalCount: number) => void,
  forceRefresh: boolean = false
): Promise<Subtitle[]> {
  if (!episodeIds || episodeIds.length === 0) {
    return [];
  }

  const refreshText = forceRefresh ? ' (强制刷新)' : '';
  console.log(`🎯 开始流式获取字幕数据${refreshText}: 剧集数量=${episodeIds.length}, IDs=[${episodeIds.slice(0, 5).join(', ')}${episodeIds.length > 5 ? '...' : ''}]`);

  return await getStreamingSubtitles(episodeIds, onProgress, forceRefresh);
}

/**
 * 根据短剧ID获取字幕列表 (新版API - 直接查询，支持多页)
 * @param shortDramaId 短剧ID
 * @param onProgress 进度回调函数
 * @param forceRefresh 是否强制刷新，忽略缓存
 */
export async function getSubtitlesByShortDramaId(
  shortDramaId: number,
  onProgress?: (subtitles: Subtitle[], completedCount: number, totalCount: number) => void,
  forceRefresh: boolean = false
): Promise<Subtitle[]> {
  if (!shortDramaId || shortDramaId <= 0) {
    return [];
  }

  const refreshText = forceRefresh ? ' (强制刷新)' : '';
  console.log(`🎯 开始获取字幕数据${refreshText}: 短剧ID=${shortDramaId}`);

  const cacheKey = `subtitles_short_drama_${shortDramaId}`;
  
  // 检查缓存（除非强制刷新）
  if (!forceRefresh) {
    const cached = cacheManager.get<Subtitle[]>(cacheKey);
    if (cached) {
      console.log(`✅ 字幕缓存命中: 短剧ID=${shortDramaId}, 字幕数量=${cached.length}`);
      onProgress?.(cached, 1, 1);
      return cached;
    }
  } else {
    console.log(`🔄 强制刷新: 忽略缓存, 短剧ID=${shortDramaId}`);
    // 清除缓存
    cacheManager.delete(cacheKey);
  }

  try {
    const pageSize = 500; // 每页大小
    
    // 获取第一页数据来确定总数
    const firstPage = await getSubtitleList({
      shortDramaId,
      pageSize,
      pageNum: 1
    });

    // 检查是否有数据
    if (!firstPage.rows || firstPage.total === 0) {
      const emptyResult: Subtitle[] = [];
      cacheManager.set(cacheKey, emptyResult, 2 * 60 * 1000); // 空结果缓存2分钟
      onProgress?.(emptyResult, 1, 1);
      return emptyResult;
    }

    const { rows: firstPageRows, total } = firstPage;
    const allSubtitles = [...firstPageRows];
    
    console.log(`📊 字幕数据总数: ${total}, 第一页: ${firstPageRows.length}条`);

    // 如果第一页已经包含了所有数据，直接返回
    if (allSubtitles.length >= total) {
      cacheManager.set(cacheKey, allSubtitles, 10 * 60 * 1000); // 10分钟缓存
      onProgress?.(allSubtitles, 1, 1);
      console.log(`✅ 字幕获取完成${refreshText}: 短剧ID=${shortDramaId}, 字幕数量=${allSubtitles.length} (单页)`);
      return allSubtitles;
    }

    // 计算需要请求的剩余页数
    const totalPages = Math.ceil(total / pageSize);
    console.log(`📖 需要分页查询: 总页数=${totalPages}, 每页=${pageSize}条`);

    // 调用进度回调显示第一页数据
    onProgress?.(allSubtitles, 1, totalPages);

    // 并发请求剩余页面
    const concurrency = 3; // 限制并发数，避免服务器压力过大
    const remainingPages = [];
    
    for (let pageNum = 2; pageNum <= totalPages; pageNum++) {
      remainingPages.push(pageNum);
    }

    // 分批处理页面请求
    const chunks = [];
    for (let i = 0; i < remainingPages.length; i += concurrency) {
      chunks.push(remainingPages.slice(i, i + concurrency));
    }

    let completedPages = 1; // 第一页已完成

    for (const chunk of chunks) {
      const chunkPromises = chunk.map(async (pageNum) => {
        try {
          const pageResult = await getSubtitleList({
            shortDramaId,
            pageSize,
            pageNum
          });

          if (pageResult?.rows) {
            allSubtitles.push(...pageResult.rows);
            completedPages++;
            
            console.log(`✅ 第${pageNum}页完成: ${pageResult.rows.length}条字幕 (${completedPages}/${totalPages})`);
            
            // 实时更新进度
            onProgress?.(allSubtitles, completedPages, totalPages);
          }

          return pageResult?.rows || [];
        } catch (error) {
          console.error(`❌ 第${pageNum}页失败:`, error);
          completedPages++;
          onProgress?.(allSubtitles, completedPages, totalPages);
          return [];
        }
      });

      // 等待当前批次完成
      await Promise.all(chunkPromises);
    }

    // 缓存最终结果
    cacheManager.set(cacheKey, allSubtitles, 10 * 60 * 1000); // 10分钟缓存

    console.log(`✅ 字幕获取完成${refreshText}: 短剧ID=${shortDramaId}, 字幕数量=${allSubtitles.length} (多页)`);
    return allSubtitles;

  } catch (error) {
    console.error(`❌ 获取短剧${shortDramaId}字幕失败:`, error);
    
    // 缓存空结果（但不缓存太久，以便重试）
    if (!forceRefresh) {
      cacheManager.set(cacheKey, [], 2 * 60 * 1000); // 2分钟缓存
    }
    
    // 调用进度回调表示完成（即使失败）
    onProgress?.([], 1, 1);
    
    return [];
  }
}

/**
 * 流式获取多个剧集的字幕（逐个请求，实时显示）
 */
async function getStreamingSubtitles(
  episodeIds: number[],
  onProgress?: (subtitles: Subtitle[], completedCount: number, totalCount: number) => void,
  forceRefresh: boolean = false
): Promise<Subtitle[]> {
  const totalCount = episodeIds.length;
  let completedCount = 0;
  const allSubtitles: Subtitle[] = [];

  // 检查整体缓存（除非强制刷新）
  const cacheKey = `subtitles_episodes_${episodeIds.sort().join('_')}`;
  if (!forceRefresh) {
    const cached = cacheManager.get<Subtitle[]>(cacheKey);
    if (cached) {
      console.log(`✅ 整体缓存命中: ${episodeIds.length}个剧集`);
      onProgress?.(cached, totalCount, totalCount);
      return cached;
    }
  } else {
    console.log(`🔄 强制刷新: 忽略所有缓存`);
    // 清除相关缓存
    cacheManager.delete(cacheKey);
    episodeIds.forEach(id => {
      cacheManager.delete(`subtitles_episode_${id}`);
    });
  }

  // 分离缓存和未缓存的剧集
  const cachedResults: Subtitle[] = [];
  const uncachedEpisodeIds: number[] = [];

  if (!forceRefresh) {
    // 正常模式：检查单个剧集缓存
    for (const episodeId of episodeIds) {
      const singleCacheKey = `subtitles_episode_${episodeId}`;
      const singleCached = cacheManager.get<Subtitle[]>(singleCacheKey);

      if (singleCached) {
        cachedResults.push(...singleCached);
        completedCount++;
      } else {
        uncachedEpisodeIds.push(episodeId);
      }
    }
  } else {
    // 强制刷新模式：所有剧集都需要重新请求
    uncachedEpisodeIds.push(...episodeIds);
  }

  // 如果有缓存数据，先显示
  if (cachedResults.length > 0) {
    allSubtitles.push(...cachedResults);
    console.log(`✅ 部分缓存命中: ${completedCount}/${totalCount}个剧集`);
    onProgress?.(allSubtitles, completedCount, totalCount);
  }

  // 如果所有数据都在缓存中，直接返回
  if (uncachedEpisodeIds.length === 0) {
    cacheManager.set(cacheKey, allSubtitles, 10 * 60 * 1000);
    return allSubtitles;
  }

  console.log(`🔄 开始流式请求: ${uncachedEpisodeIds.length}个剧集`);

  // 流式请求未缓存的剧集
  const concurrency = 8; // 个人专用，提高并发数加快加载速度
  const chunks = [];
  for (let i = 0; i < uncachedEpisodeIds.length; i += concurrency) {
    chunks.push(uncachedEpisodeIds.slice(i, i + concurrency));
  }

  for (const chunk of chunks) {
    const chunkPromises = chunk.map(async (episodeId) => {
      try {
        const result = await getSingleEpisodeSubtitlesWithPaging(episodeId, forceRefresh);

        // 立即更新结果并通知进度
        allSubtitles.push(...result);
        completedCount++;

        const refreshText = forceRefresh ? ' (刷新)' : '';
        console.log(`✅ 剧集${episodeId}完成${refreshText}: ${result.length}条字幕 (${completedCount}/${totalCount})`);

        // 实时回调进度
        onProgress?.(allSubtitles, completedCount, totalCount);

        return result;
      } catch (error) {
        console.error(`❌ 剧集${episodeId}失败:`, error);
        completedCount++;
        onProgress?.(allSubtitles, completedCount, totalCount);
        return [];
      }
    });

    // 等待当前批次完成
    await Promise.all(chunkPromises);
  }

  // 缓存最终结果
  cacheManager.set(cacheKey, allSubtitles, 10 * 60 * 1000);

  console.log(`✅ 流式加载完成: 总计${allSubtitles.length}条字幕`);
  return allSubtitles;
}



/**
 * 获取单个剧集的字幕（带分页，防止遗漏）
 */
async function getSingleEpisodeSubtitlesWithPaging(episodeId: number, forceRefresh: boolean = false): Promise<Subtitle[]> {
  const cacheKey = `subtitles_episode_${episodeId}`;

  // 尝试从缓存获取（除非强制刷新）
  if (!forceRefresh) {
    const cached = cacheManager.get<Subtitle[]>(cacheKey);
    if (cached) {
      return cached;
    }
  }

  try {
    // 使用分页参数防止遗漏数据
    const result = await getSubtitleList({
      episodeId,
      pageSize: 500,  // 大页面防止遗漏
      pageNum: 1       // 从第一页开始
    });

    const subtitles = result?.rows || [];

    // 缓存结果
    cacheManager.set(cacheKey, subtitles, 10 * 60 * 1000);

    return subtitles;
  } catch (error) {
    console.error(`获取剧集${episodeId}字幕失败:`, error);
    // 缓存空结果（但不缓存太久，以便重试）
    if (!forceRefresh) {
      cacheManager.set(cacheKey, [], 2 * 60 * 1000);
    }
    return [];
  }
}





/**
 * 获取所有字幕列表, 会自动处理分页以获取全部数据
 */
export async function getAllSubtitles(): Promise<Subtitle[]> {
  const cacheKey = 'all_subtitles';

  // 尝试从缓存获取
  const cached = cacheManager.get<Subtitle[]>(cacheKey);
  if (cached) {
    return cached;
  }

  const pageSize = 500; // 减少单页大小，避免请求过大

  const fetchPage = (pageNum: number) => getSubtitleList({ pageNum, pageSize });

  // 获取第一页数据来确定总数
  const firstPage = await fetchPage(1);

  // 检查是否有数据
  if (!firstPage.rows || firstPage.total === 0) {
    const emptyResult: Subtitle[] = [];
    cacheManager.set(cacheKey, emptyResult, 2 * 60 * 1000); // 空结果缓存2分钟
    return emptyResult;
  }

  const { rows: firstPageRows, total } = firstPage;
  const allSubtitles = firstPageRows;

  // 如果第一页已经包含了所有数据，直接返回
  if (allSubtitles.length >= total) {
    cacheManager.set(cacheKey, allSubtitles, 5 * 60 * 1000); // 5分钟缓存
    return allSubtitles;
  }

  // 计算需要请求的剩余页数
  const totalPages = Math.ceil(total / pageSize);
  const requests = [];
  for (let pageNum = 2; pageNum <= totalPages; pageNum++) {
    requests.push({
      requestFn: () => fetchPage(pageNum),
      config: {
        url: '/api/asimplefox/short/drama/subtitle/list',
        params: { pageNum, pageSize },
        method: 'GET' as const
      }
    });
  }

  // 使用批量请求管理器，字幕数据较多，限制并发数
  const remainingPages = await requestManager.batchRequest(requests, {
    concurrency: 2, // 更保守的并发数
    failFast: false
  });

  // 合并所有页面的结果
  for (const page of remainingPages) {
    if (page?.rows) {
      allSubtitles.push(...page.rows);
    }
  }

  // 缓存结果
  cacheManager.set(cacheKey, allSubtitles, 5 * 60 * 1000); // 5分钟缓存
  return allSubtitles;
}

// ================== 搜索功能API ==================

/**
 * 快速搜索 - 基于标题的简单搜索
 * @param keyword 搜索关键词
 * @param pageNum 页码
 * @param pageSize 每页大小
 */
export async function quickSearch(
  keyword: string, 
  pageNum: number = 1, 
  pageSize: number = 20
): Promise<SearchResult<Drama[]>> {
  const startTime = Date.now();

  // 参数验证
  validateRequired(keyword, '搜索关键词');
  validatePaginationParams({ pageNum, pageSize });

  const normalizedKeyword = normalizeSearchKeyword(keyword);
  if (!normalizedKeyword) {
    throw new Error('搜索关键词无效');
  }

  const searchParams: AdvancedSearchParams = {
    keyword: normalizedKeyword,
    searchType: SearchType.TITLE,
    pageNum,
    pageSize,
    sortBy: SortOrder.RELEVANCE
  };

  // 检查缓存
  const cached = searchCacheManager.getCachedSearch<SearchResult<Drama[]>>(searchParams);
  if (cached) {
    return cached;
  }

  try {
    const params = buildSearchParams(searchParams);
    const result = await getDramaList(params);

    const searchResult: SearchResult<Drama[]> = {
      ...result,
      searchKeyword: keyword,
      searchTime: Date.now() - startTime
    };

    // 缓存结果
    searchCacheManager.setCachedSearch(searchParams, searchResult);
    return searchResult;
  } catch (error) {
    console.error('快速搜索失败:', error);
    throw error instanceof Error ? error : new Error(`搜索失败: ${error}`);
  }
}

/**
 * 高级搜索 - 支持多种筛选条件的复杂搜索
 * @param params 高级搜索参数
 */
export async function advancedSearch(params: AdvancedSearchParams): Promise<SearchResult<Drama[]>> {
  const startTime = Date.now();

  // 参数验证
  if (params.pageNum !== undefined || params.pageSize !== undefined) {
    validatePaginationParams({ pageNum: params.pageNum, pageSize: params.pageSize });
  }

  // 标准化搜索参数
  const normalizedParams = { ...params };
  if (params.keyword) {
    normalizedParams.keyword = normalizeSearchKeyword(params.keyword);
    if (!normalizedParams.keyword) {
      throw new Error('搜索关键词无效');
    }
  }

  // 检查缓存
  const cached = searchCacheManager.getCachedSearch<SearchResult<Drama[]>>(normalizedParams);
  if (cached) {
    return cached;
  }

  try {
    const searchApiParams = buildSearchParams(normalizedParams);
    const result = await getDramaList(searchApiParams);

    const searchResult: SearchResult<Drama[]> = {
      ...result,
      searchKeyword: params.keyword,
      searchTime: Date.now() - startTime
    };

    // 如果有搜索关键词，生成搜索建议
    if (params.keyword) {
      searchResult.suggestions = await generateSearchSuggestions(params.keyword, result.rows);
    }

    // 缓存结果
    searchCacheManager.setCachedSearch(normalizedParams, searchResult);
    return searchResult;
  } catch (error) {
    console.error('高级搜索失败:', error);
    throw error instanceof Error ? error : new Error(`高级搜索失败: ${error}`);
  }
}

/**
 * 防抖搜索 - 用于实时搜索，避免频繁请求
 * @param keyword 搜索关键词
 * @param onResults 结果回调函数
 * @param options 搜索选项
 */
export function debouncedSearch(
  keyword: string,
  onResults: (results: SearchResult<Drama[]>) => void,
  options: {
    delay?: number;
    pageSize?: number;
    searchType?: SearchType;
  } = {}
): void {
  const { delay = 300, pageSize = 10 } = options;

  const searchKey = `debounced_search_${keyword}`;
  
  const debouncedFn = searchDebouncer.debounce(
    searchKey,
    async () => {
      try {
        if (!keyword.trim()) {
          onResults({ rows: [], total: 0, code: 200, msg: '', searchTime: 0 });
          return;
        }

        const results = await quickSearch(keyword, 1, pageSize);
        onResults(results);
      } catch (error) {
        console.error('防抖搜索失败:', error);
        onResults({ 
          rows: [], 
          total: 0, 
          code: 500, 
          msg: error instanceof Error ? error.message : '搜索失败',
          searchTime: 0 
        });
      }
    },
    delay
  );

  debouncedFn();
}

/**
 * 取消防抖搜索
 * @param keyword 搜索关键词
 */
export function cancelDebouncedSearch(keyword: string): void {
  const searchKey = `debounced_search_${keyword}`;
  searchDebouncer.cancel(searchKey);
}

/**
 * 生成搜索建议
 * @param keyword 原始关键词
 * @param results 搜索结果
 */
async function generateSearchSuggestions(keyword: string, results: Drama[]): Promise<string[]> {
  // 检查缓存的建议
  const cached = searchCacheManager.getCachedSuggestions(keyword);
  if (cached) {
    return cached;
  }

  const suggestions: string[] = [];

  // 基于搜索结果生成建议
  if (results && results.length > 0) {
    // 提取标题中的关键词
    const titleKeywords = new Set<string>();
    
    results.forEach(drama => {
      if (drama.title) {
        // 简单的关键词提取（可以进一步优化）
        const words = drama.title
          .replace(/[^\w\s\u4e00-\u9fa5]/g, ' ')
          .split(/\s+/)
          .filter(word => word.length > 1);
        
        words.forEach(word => titleKeywords.add(word));
      }

      // 提取分类
      if (drama.categoryName && Array.isArray(drama.categoryName)) {
        drama.categoryName.forEach(category => {
          if (category && category !== keyword) {
            titleKeywords.add(category);
          }
        });
      }
    });

    // 过滤和排序建议
    suggestions.push(
      ...Array.from(titleKeywords)
        .filter(word => 
          word.toLowerCase().includes(keyword.toLowerCase()) ||
          keyword.toLowerCase().includes(word.toLowerCase())
        )
        .slice(0, 5) // 限制建议数量
    );
  }

  // 缓存建议
  searchCacheManager.setCachedSuggestions(keyword, suggestions);
  return suggestions;
}

/**
 * 获取搜索筛选器信息
 * @param keyword 可选的关键词，用于获取相关筛选器
 */
export async function getSearchFilters(keyword?: string): Promise<SearchFilters> {
  const cacheKey = generateCacheKey('search_filters', { keyword: keyword || '' });
  
  // 尝试从缓存获取
  const cached = cacheManager.get<SearchFilters>(cacheKey);
  if (cached) {
    return cached;
  }

  try {
    // 获取所有短剧来分析筛选器选项
    // 注意：这里可能需要优化为专门的筛选器API
    const allDramas = await getAllDramas();

    const filters: SearchFilters = {
      availableCategories: [],
      availableStatuses: [],
      availableSpecialTags: [],
      scoreRange: [0, 10],
      episodeRange: [1, 100]
    };

    if (allDramas.length > 0) {
      // 统计分类
      const categoryMap = new Map<string, number>();
      const statusMap = new Map<number, number>();
      const specialTagMap = new Map<string, number>();
      const scores: number[] = [];
      const episodes: number[] = [];

      allDramas.forEach(drama => {
        // 统计分类
        if (drama.categoryName && Array.isArray(drama.categoryName)) {
          drama.categoryName.forEach(category => {
            categoryMap.set(category, (categoryMap.get(category) || 0) + 1);
          });
        }

        // 统计状态
        if (drama.status !== undefined) {
          statusMap.set(drama.status, (statusMap.get(drama.status) || 0) + 1);
        }

        // 统计特殊标签
        if (drama.special) {
          specialTagMap.set(drama.special, (specialTagMap.get(drama.special) || 0) + 1);
        }

        // 收集评分
        if (drama.score) {
          const numericScore = parseFloat(drama.score);
          if (!isNaN(numericScore)) {
            scores.push(numericScore);
          }
        }

        // 收集集数
        if (drama.episodeCount) {
          episodes.push(drama.episodeCount);
        }
      });

      // 构建筛选器选项
      filters.availableCategories = Array.from(categoryMap.entries())
        .map(([name, count]) => ({ name, count }))
        .sort((a, b) => b.count - a.count);

      filters.availableStatuses = Array.from(statusMap.entries())
        .map(([status, count]) => ({ 
          status, 
          name: getStatusName(status), 
          count 
        }))
        .sort((a, b) => a.status - b.status);

      filters.availableSpecialTags = Array.from(specialTagMap.entries())
        .map(([tag, count]) => ({ tag, count }))
        .sort((a, b) => b.count - a.count);

      // 计算范围
      if (scores.length > 0) {
        filters.scoreRange = [Math.min(...scores), Math.max(...scores)];
      }

      if (episodes.length > 0) {
        filters.episodeRange = [Math.min(...episodes), Math.max(...episodes)];
      }
    }

    // 缓存筛选器信息
    cacheManager.set(cacheKey, filters, 30 * 60 * 1000); // 30分钟缓存
    return filters;
  } catch (error) {
    console.error('获取搜索筛选器失败:', error);
    // 返回默认筛选器
    return {
      availableCategories: [],
      availableStatuses: [],
      availableSpecialTags: [],
      scoreRange: [0, 10],
      episodeRange: [1, 100]
    };
  }
}

/**
 * 获取状态名称（辅助函数）
 */
function getStatusName(status: number): string {
  const statusNames: Record<number, string> = {
    0: '启用',
    1: '禁用',
    2: '草稿',
    3: '待审核'
  };
  return statusNames[status] || `状态${status}`;
}

/**
 * 清除搜索缓存
 */
export function clearSearchCache(): void {
  searchCacheManager.clearSearchCache();
  searchDebouncer.clear();
}

// ================== 字幕删除功能API ==================

/**
 * 根据剧集ID批量删除字幕
 * @param episodeIds 剧集ID数组
 * @description 批量删除操作可能耗时较长，已设置60秒超时时间
 */
export async function deleteSubtitlesByEpisodes(episodeIds: number[]): Promise<{ success: boolean; message: string; deletedCount: number }> {
  // 参数验证
  if (!episodeIds || episodeIds.length === 0) {
    throw new Error('episodeIds不能为空');
  }

  // 验证所有ID都是有效的正整数
  const validIds = episodeIds.filter(id => typeof id === 'number' && id > 0);
  if (validIds.length !== episodeIds.length) {
    throw new Error('所有剧集ID必须是有效的正整数');
  }

  const config = {
    url: '/api/asimplefox/short/drama/subtitle/deleteByEpisodes',
    method: 'POST' as const,
    headers: {
      'accept': 'application/json',
      'Content-Type': 'application/json'
    },
    data: validIds  // 直接发送整数数组，不包装在对象中
  };

  try {
    console.log(`🗑️ 开始批量删除字幕: ${validIds.length}个剧集ID=[${validIds.slice(0, 5).join(', ')}${validIds.length > 5 ? '...' : ''}]`);
    console.log(`⏰ 提醒: 批量删除操作可能需要较长时间，请耐心等待...`);
    console.log(`📤 请求URL: ${config.url}`);
    console.log(`📋 请求数据(剧集ID数组):`, JSON.stringify(config.data, null, 2));

    const result = await requestManager.request(
      () => request({
        method: 'POST',
        url: config.url,
        headers: config.headers,
        data: config.data,
        timeout: 1800000 // 批量删除操作超时时间设为60秒
      }),
      config,
      { enableDeduplication: false } // 删除操作不启用去重
    );
    
    console.log(`📥 响应数据:`, JSON.stringify(result, null, 2));
    // 使用统一响应处理
    const normalizedResponse = normalizeApiResponse<any>(result);
    
    if (!normalizedResponse.success) {
      throw new Error(normalizedResponse.message || '删除字幕失败');
    }

    console.log(`✅ 字幕删除成功: ${validIds.length}个剧集`);

    // 清除相关缓存
    clearSubtitleRelatedCache(validIds);

    return {
      success: true,
      message: normalizedResponse.message || '删除成功',
      deletedCount: validIds.length
    };
  } catch (error) {
    console.error('删除字幕失败:', error);
    throw error instanceof Error ? error : new Error(`删除字幕失败: ${error}`);
  }
}

/**
 * 根据剧集ID删除单集的所有字幕
 * @param episodeId 剧集ID
 * @description 删除操作可能耗时较长，已设置30秒超时时间
 */
export async function deleteEpisodeSubtitleByEpisodeId(
  episodeId: number
): Promise<{ success: boolean; message: string; deletedCount: number }> {
  // 参数验证
  validateRequired(episodeId, 'episodeId');
  const numericEpisodeId = safeParseInt(episodeId, '剧集ID');

  const config = {
    url: `/api/asimplefox/short/drama/subtitle/episode/${numericEpisodeId}`,
    method: 'DELETE' as const,
    headers: {
      'accept': 'application/json'
    }
  };

  try {
    console.log(`🎯 删除剧集${numericEpisodeId}的字幕`);
    console.log(`⏰ 提醒: 删除操作可能需要较长时间，请耐心等待...`);
    console.log(`📤 请求URL: ${config.url}`);

    const result = await requestManager.request(
      () => request({
        method: 'DELETE',
        url: config.url,
        headers: config.headers,
        timeout: 300000 // 单集删除操作超时时间设为30秒
      }),
      config,
      { enableDeduplication: false } // 删除操作不启用去重
    );
    
    console.log(`📥 响应数据:`, JSON.stringify(result, null, 2));
    // 使用统一响应处理
    const normalizedResponse = normalizeApiResponse<any>(result);
    
    if (!normalizedResponse.success) {
      throw new Error(normalizedResponse.message || '删除字幕失败');
    }

    console.log(`✅ 剧集${numericEpisodeId}字幕删除完成`);

    // 清除相关缓存
    clearSubtitleRelatedCache([numericEpisodeId]);

    return {
      success: true,
      message: normalizedResponse.message || '删除成功',
      deletedCount: 1 // 删除了一个剧集的字幕
    };
  } catch (error) {
    console.error(`删除剧集${numericEpisodeId}字幕失败:`, error);
    throw error instanceof Error ? error : new Error(`删除剧集字幕失败: ${error}`);
  }
}

/**
 * @deprecated 请使用 deleteEpisodeSubtitleByEpisodeId 代替
 * 删除单集的所有字幕（兼容旧版本）
 * @param episodeId 剧集ID
 * @param subtitles 当前字幕列表（已废弃，不再使用）
 */
export async function deleteEpisodeSubtitles(
  episodeId: number): Promise<{ success: boolean; message: string; deletedCount: number }> {
  console.warn('deleteEpisodeSubtitles 已废弃，请使用 deleteEpisodeSubtitleByEpisodeId');
  return await deleteEpisodeSubtitleByEpisodeId(episodeId);
}

/**
 * 批量删除指定剧集的字幕（支持自选剧集，分批删除，每次最多20集）
 * @param episodeIds 要删除的剧集ID数组
 * @param onProgress 进度回调函数
 */
export async function deleteBatchEpisodeSubtitles(
  episodeIds: number[],
  onProgress?: (deletedEpisodes: number, totalEpisodes: number, currentBatch: number, totalBatches: number) => void
): Promise<{ success: boolean; message: string; deletedCount: number }> {
  // 参数验证
  if (!episodeIds || episodeIds.length === 0) {
    return {
      success: true,
      message: '没有需要删除的剧集',
      deletedCount: 0
    };
  }

  // 验证所有ID都是有效的正整数
  const validIds = episodeIds.filter(id => typeof id === 'number' && id > 0);
  if (validIds.length !== episodeIds.length) {
    throw new Error('所有剧集ID必须是有效的正整数');
  }

  const totalEpisodes = validIds.length;
  const batchSize = 300; // 每次处理最多20集
  const totalBatches = Math.ceil(totalEpisodes / batchSize);
  
  console.log(`🎯 开始批量删除字幕: ${totalEpisodes}集，分${totalBatches}批处理`);

  let totalDeletedCount = 0;
  let deletedEpisodes = 0;

  try {
    // 分批处理
    for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) {
      const startIndex = batchIndex * batchSize;
      const endIndex = Math.min(startIndex + batchSize, totalEpisodes);
      const batchEpisodeIds = validIds.slice(startIndex, endIndex);
      
      console.log(`📦 处理第${batchIndex + 1}/${totalBatches}批: 剧集${batchEpisodeIds[0]}-${batchEpisodeIds[batchEpisodeIds.length - 1]} (${batchEpisodeIds.length}集)`);

      if (batchEpisodeIds.length > 0) {
        // 使用批量删除API，直接传入剧集ID数组
        const batchResult = await deleteSubtitlesByEpisodes(batchEpisodeIds);
        totalDeletedCount += batchResult.deletedCount;
        deletedEpisodes += batchEpisodeIds.length;

        console.log(`✅ 第${batchIndex + 1}批删除完成: ${batchEpisodeIds.length}个剧集 (进度: ${deletedEpisodes}/${totalEpisodes}集)`);

        // 调用进度回调
        onProgress?.(deletedEpisodes, totalEpisodes, batchIndex + 1, totalBatches);

        // 批次之间稍作延迟，避免服务器压力过大
        if (batchIndex < totalBatches - 1) {
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      }
    }

    console.log(`✅ 批量删除字幕完成: 总计${deletedEpisodes}集`);

    return {
      success: true,
      message: `成功删除${deletedEpisodes}集字幕`,
      deletedCount: deletedEpisodes
    };
  } catch (error) {
    console.error(`批量删除字幕失败:`, error);
    throw error instanceof Error ? error : new Error(`批量删除字幕失败: ${error}`);
  }
}

/**
 * 批量删除整部剧的字幕（分批删除，每次最多20集）
 * @param shortDramaId 短剧ID
 * @param subtitles 当前字幕列表（用于获取该短剧的剧集ID列表）
 * @param onProgress 进度回调函数
 */
export async function deleteDramaSubtitles(
  shortDramaId: number,
  subtitles: Subtitle[],
  onProgress?: (deletedEpisodes: number, totalEpisodes: number, currentBatch: number, totalBatches: number) => void
): Promise<{ success: boolean; message: string; deletedCount: number }> {
  // 参数验证
  validateRequired(shortDramaId, 'shortDramaId');
  const numericDramaId = safeParseInt(shortDramaId, '短剧ID');

  // 找到该短剧的所有字幕，按剧集分组
  const dramaSubtitles = subtitles.filter(subtitle => subtitle.shortDramaId === numericDramaId);
  
  if (dramaSubtitles.length === 0) {
    return {
      success: true,
      message: `短剧${numericDramaId}没有字幕需要删除`,
      deletedCount: 0
    };
  }

  // 按剧集ID分组，获取唯一的剧集ID列表
  const episodeGroups = new Map<number, Subtitle[]>();
  dramaSubtitles.forEach(subtitle => {
    const episodeId = subtitle.episodeId;
    if (!episodeGroups.has(episodeId)) {
      episodeGroups.set(episodeId, []);
    }
    episodeGroups.get(episodeId)!.push(subtitle);
  });

  const episodeIds = Array.from(episodeGroups.keys()).sort((a, b) => a - b);
  console.log(`🎯 开始删除短剧${numericDramaId}的字幕: ${episodeIds.length}集`);

  // 直接使用新的批量删除函数
  return await deleteBatchEpisodeSubtitles(episodeIds, onProgress);
}

/**
 * 清除字幕相关缓存
 * @param episodeIds 剧集ID数组（从字幕ID改为剧集ID，因为新API使用剧集ID删除）
 */
function clearSubtitleRelatedCache(episodeIds: number[]): void {
  console.log(`🧹 清除字幕相关缓存: ${episodeIds.length}个剧集`);
  
  // 清除全局字幕缓存
  cacheManager.delete('all_subtitles');
  
  // 清除具体剧集的缓存
  episodeIds.forEach(episodeId => {
    cacheManager.delete(`subtitles_episode_${episodeId}`);
  });
  
  // 由于不知道具体的缓存key，这里使用通用方法
  // 实际项目中可以根据cacheManager的实现来优化
  
  // 清除可能存在的缓存（假设有这些缓存）
  const commonCachePatterns = [
    'subtitles_short_drama_',
    'subtitles_episodes_',
    'subtitle_status_'
  ];
  
  // 由于无法直接按前缀清除，这里只是记录日志
  // 实际的缓存清理会在下次加载时自然发生
  commonCachePatterns.forEach(pattern => {
    console.log(`标记清除缓存模式: ${pattern}*`);
  });
  
  console.log(`✅ 字幕缓存清理完成，相关数据将在下次访问时重新加载`);
}

// ================== 字幕状态功能API ==================

/**
 * 获取短剧的字幕完成状态
 * @param shortDramaId 短剧ID
 */
export async function getSubtitleCompletionStatus(shortDramaId: string | number): Promise<SubtitleCompletionStatus> {
  // 参数验证
  validateRequired(shortDramaId, 'shortDramaId');
  const numericDramaId = safeParseInt(shortDramaId, '短剧ID');
  
  const cacheKey = `subtitle_status_${numericDramaId}`;

  // 尝试从缓存获取（短时间缓存，状态可能变化较快）
  const cached = cacheManager.get<SubtitleCompletionStatus>(cacheKey);
  if (cached) {
    return cached;
  }

  const config = {
    url: `/api/asimplefox/short/drama/subtitle/checkStatus/${numericDramaId}`,
    method: 'GET' as const
  };

  try {
    const result = await requestManager.request(
      () => request.get<SimpleApiResult<SubtitleCompletionStatus>, SimpleApiResult<SubtitleCompletionStatus>>(config.url),
      config,
      { enableDeduplication: true }
    );

    // 使用统一响应处理
    const normalizedResponse = normalizeApiResponse<SubtitleCompletionStatus>(result);
    
    if (!normalizedResponse.success) {
      throw new Error(normalizedResponse.message || `获取字幕完成状态失败 (短剧ID: ${numericDramaId})`);
    }

    const status = normalizedResponse.data;
    if (!status) {
      throw new Error(`未找到短剧ID为 ${numericDramaId} 的字幕状态信息`);
    }

    // 缓存结果（短时间缓存，2分钟）
    cacheManager.set(cacheKey, status, 2 * 60 * 1000);
    
    console.log(`✅ 字幕状态查询成功: 短剧ID=${numericDramaId}, 状态=${status.subtitleStatus === 0 ? '完成' : '未完成'}, 进度=${status.uploadedSubtitles}/${status.totalEpisodes}`);
    
    return status;
  } catch (error) {
    console.error(`获取字幕完成状态失败 (短剧ID: ${numericDramaId}):`, error);
    throw error instanceof Error ? error : new Error(`获取字幕完成状态失败: ${error}`);
  }
}

/**
 * 批量获取多个短剧的字幕完成状态
 * @param shortDramaIds 短剧ID数组
 * @param onProgress 进度回调函数
 */
export async function getBatchSubtitleCompletionStatus(
  shortDramaIds: number[],
  onProgress?: (statuses: Map<number, SubtitleCompletionStatus>, completedCount: number, totalCount: number) => void
): Promise<Map<number, SubtitleCompletionStatus>> {
  if (!shortDramaIds || shortDramaIds.length === 0) {
    return new Map();
  }

  console.log(`🎯 开始批量获取字幕状态: 短剧数量=${shortDramaIds.length}, IDs=[${shortDramaIds.slice(0, 5).join(', ')}${shortDramaIds.length > 5 ? '...' : ''}]`);

  const statusMap = new Map<number, SubtitleCompletionStatus>();
  let completedCount = 0;
  const totalCount = shortDramaIds.length;

  // 检查缓存
  const uncachedIds: number[] = [];
  for (const id of shortDramaIds) {
    const cacheKey = `subtitle_status_${id}`;
    const cached = cacheManager.get<SubtitleCompletionStatus>(cacheKey);
    if (cached) {
      statusMap.set(id, cached);
      completedCount++;
    } else {
      uncachedIds.push(id);
    }
  }

  // 如果有缓存数据，先显示
  if (statusMap.size > 0) {
    console.log(`✅ 部分缓存命中: ${completedCount}/${totalCount}个短剧`);
    onProgress?.(statusMap, completedCount, totalCount);
  }

  // 如果所有数据都在缓存中，直接返回
  if (uncachedIds.length === 0) {
    return statusMap;
  }

  console.log(`🔄 开始流式请求字幕状态: ${uncachedIds.length}个短剧`);

  // 并发请求未缓存的状态
  const concurrency = 5; // 限制并发数，避免服务器压力过大
  const chunks = [];
  for (let i = 0; i < uncachedIds.length; i += concurrency) {
    chunks.push(uncachedIds.slice(i, i + concurrency));
  }

  for (const chunk of chunks) {
    const chunkPromises = chunk.map(async (dramaId) => {
      try {
        const status = await getSubtitleCompletionStatus(dramaId);
        statusMap.set(dramaId, status);
        completedCount++;

        console.log(`✅ 短剧${dramaId}状态获取完成: ${status.subtitleStatus === 0 ? '完成' : '未完成'} (${completedCount}/${totalCount})`);

        // 实时回调进度
        onProgress?.(statusMap, completedCount, totalCount);

        return status;
      } catch (error) {
        console.error(`❌ 短剧${dramaId}状态获取失败:`, error);
        completedCount++;
        onProgress?.(statusMap, completedCount, totalCount);
        return null;
      }
    });

    // 等待当前批次完成
    await Promise.all(chunkPromises);
  }

  console.log(`✅ 批量状态查询完成: 总计${statusMap.size}个短剧状态获取成功`);
  return statusMap;
}
